package com.qding.park.manager.service.queue.facade.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import com.qding.park.common.core.exceptions.IExceptionHandle;
import com.qding.park.common.utils.ListUtil;
import com.qding.park.common.utils.OrderNumUtil;
import com.qding.park.manager.cache.ParkCacheInter;
import com.qding.park.manager.cache.UserCacheInter;
import com.qding.park.manager.facade.queue.service.EventWriteBack;
import com.qding.park.manager.pojo.TbCar;
import com.qding.park.manager.pojo.TbFeetrade;
import com.qding.park.manager.pojo.TbMonthRent;
import com.qding.park.manager.pojo.TbParkspace;
import com.qding.park.manager.pojo.TbReserve;
import com.qding.park.manager.pojo.ap.ApAppearanceRecord;
import com.qding.park.manager.pojo.enums.OrderServiceType;
import com.qding.park.manager.pojo.enums.OrderSourceEnum;
import com.qding.park.manager.pojo.enums.ParkFeeModelEnum;
import com.qding.park.manager.pojo.enums.RecordStatusEnum;
import com.qding.park.manager.pojo.enums.ReserverStatusEnum;
import com.qding.park.manager.pojo.enums.ReserverTypeEnum;
import com.qding.park.manager.pojo.noncore.NcMonthRent;
import com.qding.park.manager.pojo.noncore.NcTempPayInfo;
import com.qding.park.manager.service.queue.dao.MongodbDao;
import com.qding.park.manager.service.queue.mapper.TbCarMapper;
import com.qding.park.manager.service.queue.mapper.TbFeetradeMapper;
import com.qding.park.manager.service.queue.mapper.TbReserveMapper;

/**
 * @author Administrator 事件回写
 */
@Service("eventWriteBack")
public class EventWriteBackImpl implements EventWriteBack {

	private static final Log _log = LogFactory.getLog(EventWriteBackImpl.class);

	@Autowired
	private IExceptionHandle exceptionHandle;

	@Autowired
	private MongodbDao mongodbDao;

	@Autowired
	private UserCacheInter userCacheInter;
	
	@Autowired
	private ParkCacheInter parkCacheInter;
	
	@Autowired
	private  TbCarMapper tbCarMapper  ;

	@Autowired
	private  TbReserveMapper  tbReserveMapper;
	
	@Autowired
	private  TbFeetradeMapper  tbFeetradeMapper;
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.qding.park.manager.facade.statis.service.EventWriteBack#
	 * MonthPayComplete(com.qding.park.manager.pojo.TbMonthRent) 月租单生效日志回写
	 */
	@Override
	public void MonthPayComplete(TbMonthRent tbMonthRent) {

		try {
			
			String bjuserid = userCacheInter.userId2bjuserId(String.valueOf(tbMonthRent.getUserID()));
			String tel = userCacheInter.userId2tel(String.valueOf(tbMonthRent.getUserID()));
			TbParkspace parkspace=parkCacheInter.queryParkSpace(tbMonthRent.getParkID());
			int supplierId=parkspace.getSupplierId();
			NcMonthRent ncMonthRent = new NcMonthRent();
			ncMonthRent.setAddFeeMode(ParkFeeModelEnum.APP.getType());
			ncMonthRent.setBjOrderId(tbMonthRent.getBjOrderId());
			ncMonthRent.setBjuserid(bjuserid);
			ncMonthRent.setBuyMonths(tbMonthRent.getBuyMonths());
			ncMonthRent.setCarNum(tbMonthRent.getCarNum());
			ncMonthRent.setCreate_date(new Date());
			ncMonthRent.setMonthlyEndTime(tbMonthRent.getExpiredate());
			ncMonthRent.setMonthlyStartTime(tbMonthRent.getOldExpiredate());
			ncMonthRent.setOrderSource(tbMonthRent.getOrderSource());
			ncMonthRent.setParkID(tbMonthRent.getParkID());
			ncMonthRent.setParkName(tbMonthRent.getParkName());
			ncMonthRent.setParkPayId(tbMonthRent.getParkOrderId());
			ncMonthRent.setPay_channel(TbFeetrade.ChannelEnum.CAPITALFLOW_LINE.getType());
			ncMonthRent.setPaymentAmount(tbMonthRent.getRealPayCost());
			ncMonthRent.setPayOrderID(tbMonthRent.getId());
			ncMonthRent.setRechargeDate(tbMonthRent.getCreate_date());
			ncMonthRent.setShouldPaymentAmount(tbMonthRent.getCost());
			ncMonthRent.setStatus(RecordStatusEnum.EFFICIENCY.getStatus());
			ncMonthRent.setTradeID(tbMonthRent.getTradeID());
			ncMonthRent.setUpdate_date(new Date());
			ncMonthRent.setUserId(tbMonthRent.getUserID());
			ncMonthRent.setMonthlyBuyFee(tbMonthRent.getCost());
			ncMonthRent.setSupplyID(String.valueOf(supplierId));
			ncMonthRent.setTel(tel);
			mongodbDao.saveNcMonthRent(ncMonthRent);

		} catch (Throwable e) {
			exceptionHandle.handle(e);
			_log.error(e, e);
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.qding.park.manager.facade.statis.service.EventWriteBack#
	 * Park_ParkOutSync(com.qding.park.manager.pojo.ap.ApAppearanceRecord)
	 * 支付回写
	 */
	@Override
	public void Park_ParkOutSync(ApAppearanceRecord apAppearanceRecord) {
		
		String parkCode=apAppearanceRecord.getParkId();
		int supplierId=Integer.valueOf(apAppearanceRecord.getSupplyID());
		TbParkspace  tbParkspace=parkCacheInter.queryParkSpace(parkCode, supplierId);
		
		List<String> appOrderIds=new ArrayList<String>();
		String orderId="";
		try{
			int parkId=tbParkspace.getId();
			String carNum=apAppearanceRecord.getCarNum();
			List<TbCar> tbCars = tbCarMapper.queryCarByParkIdCarNum(parkId, carNum);
			if (StringUtils.isBlank(apAppearanceRecord.getPayOrderID())
					&&apAppearanceRecord.getShouldFeeMoney()!=0
					&&!ListUtil.isEmpty(tbCars)) {
				//修改了　只有线下且应缴金额不为0的情况才可以会和app上的历史记录相关联
				// 找到对应的车牌
//				for(TbCar car:tbCars){
//					int userId=car.getUserID();
					int userId=tbCars.get(0).getUserID();
					String tradeId=OrderNumUtil.getOrderNum(userId,OrderServiceType.FEETRADE.getTag());
					TbReserve reserver = new TbReserve();
					reserver.setParkID(parkId);
					reserver.setCarNum(carNum);
					//设置　类型为临停缴费
					reserver.setReserverType(ReserverTypeEnum.UNRESERVER.getType());
					reserver.setParkName(tbParkspace.getName());
					orderId=OrderNumUtil.getOrderNum(userId,OrderServiceType.OUTLINE_TEMP_PAY.getTag());
					appOrderIds.add(orderId);
					reserver.setId(orderId);
					reserver.setUserID(userId);
					reserver.setTradeid(tradeId);
					reserver.setDeposit(apAppearanceRecord.getShouldFeeMoney());
					reserver.setRealPayDeposit(apAppearanceRecord.getFeeMoney());
					reserver.setStatus(ReserverStatusEnum.TEMP_PAY_PARK_HANDED.getStatus());
					reserver.setCheckInTime(apAppearanceRecord.getEnterTime());
					reserver.setCheckOutTime(apAppearanceRecord.getOutTime());
					reserver.setOrderSource(OrderSourceEnum.OUTLINE.getType());
					reserver.setCreate_date(new Date());
					reserver.setUpdate_date(new Date());
					int num = tbReserveMapper.save(reserver);
					
					
					TbFeetrade tbFeetrade = new TbFeetrade();
					tbFeetrade.setId(tradeId);
					tbFeetrade.setUserID(reserver.getUserID());
					tbFeetrade.setParkID(reserver.getParkID());
					tbFeetrade.setFeeType(TbFeetrade.FeeTypeEnum.CAPITALFLOW_TEMP_PAY.getType());
					tbFeetrade.setFeeCost(reserver.getRealPayDeposit());//实付金额
					tbFeetrade.setBusinessID(reserver.getId());
					tbFeetrade.setChannel(TbFeetrade.ChannelEnum.CAPITALFLOW_LINE.getType());
					tbFeetrade.setStatus(RecordStatusEnum.EFFICIENCY.getStatus());
					// 保存流水
					int num1 = tbFeetradeMapper.save(tbFeetrade);
//				}
				
			}
			
		}catch (Throwable e) {
			exceptionHandle.handle(e);
			_log.error(e, e);
		}
		
		
		NcTempPayInfo ncTempPayInfo = new NcTempPayInfo();
		try {
			
			if(!StringUtils.isBlank(apAppearanceRecord.getPayOrderID())){
				_log.info("线上临停缴费上报");
				mongodbDao.updateLineTempPay(apAppearanceRecord);
				
				mongodbDao.updateInoutcheck(apAppearanceRecord);
				
			}else if(apAppearanceRecord.getShouldFeeMoney()!=0){
				//　　应付金额不为0   为线下临停缴费上报　
//				_log.info(message);
				ncTempPayInfo.setCardCode(apAppearanceRecord.getCardCode());
				ncTempPayInfo.setCardType(apAppearanceRecord.getCardType());
				ncTempPayInfo.setCarNum(apAppearanceRecord.getCarNum());
				ncTempPayInfo.setCarType(apAppearanceRecord.getCarType());
//				ncTempPayInfo.setCreate_date(new Date());
				ncTempPayInfo.setEnInID(apAppearanceRecord.getEnInID());
				ncTempPayInfo.setEnOutID(apAppearanceRecord.getEnOutID());
				ncTempPayInfo.setEnterTime(apAppearanceRecord.getEnterTime());
				ncTempPayInfo.setFeeMoney(apAppearanceRecord.getFeeMoney());
				ncTempPayInfo.setOpSpecial(apAppearanceRecord.getOpSpecial());
				ncTempPayInfo.setOpType(apAppearanceRecord.getOpType());
				ncTempPayInfo.setOrderSource(OrderSourceEnum.OUTLINE.getType());
				ncTempPayInfo.setOutRoomName(apAppearanceRecord.getOutRoomName());
				ncTempPayInfo.setOutTime(apAppearanceRecord.getOutTime());
				ncTempPayInfo.setParkCode(apAppearanceRecord.getParkId());
				ncTempPayInfo.setParkId(tbParkspace.getId());
				ncTempPayInfo.setRoomName(apAppearanceRecord.getRoomName());
				ncTempPayInfo.setShouldFeeMoney(apAppearanceRecord.getShouldFeeMoney());
				ncTempPayInfo.setSupplyID(apAppearanceRecord.getSupplyID());
				ncTempPayInfo.setUpdate_time(new Date());
				ncTempPayInfo.setCreate_date(apAppearanceRecord.getOutTime()==null?new Date():apAppearanceRecord.getOutTime());
				String payOrderID=(StringUtils.isBlank(orderId)?OrderNumUtil.getOrderNum(apAppearanceRecord.getSupplyID()+apAppearanceRecord.getEnOutID(), OrderServiceType.TEMP_PAY.getTag()):orderId);
//				ncTempPayInfo.setPayOrderID(apAppearanceRecord.getPayOrderID());
				ncTempPayInfo.setPayOrderID(payOrderID);
				
				mongodbDao.saveNcTempPayInfo(ncTempPayInfo);
			}
		

		} catch (Throwable e) {
			exceptionHandle.handle(e);
			_log.error(e, e);
		}
	}

	@Override
	public void temp_payed_Issued(TbReserve tbReserve) {
		NcTempPayInfo ncTempPayInfo = new NcTempPayInfo();
		ncTempPayInfo.setBjOrderId(tbReserve.getBjOrderId());
		ncTempPayInfo.setCarNum(tbReserve.getCarNum());
		ncTempPayInfo.setCreate_date(tbReserve.getCreate_date());
		ncTempPayInfo.setFeeMoney(tbReserve.getRealPayDeposit());
		ncTempPayInfo.setShouldFeeMoney(tbReserve.getDeposit());
		ncTempPayInfo.setParkId(tbReserve.getParkID());
		ncTempPayInfo.setPayOrderID(tbReserve.getId());
		ncTempPayInfo.setOrderId(tbReserve.getParkOrderId());
		
		String bjuserid = userCacheInter.userId2bjuserId(String.valueOf(tbReserve.getUserID()));
		String tel = userCacheInter.userId2tel(String.valueOf(tbReserve.getUserID()));
		ncTempPayInfo.setTel(tel);
		ncTempPayInfo.setUserId(tbReserve.getUserID());
		ncTempPayInfo.setOrderSource(tbReserve.getOrderSource());
		mongodbDao.saveNcTempPayInfo(ncTempPayInfo);
	}

}
